package com.rop.result;

import lombok.Data;

import java.util.Objects;

/**
 * @Title: Result
 * @Author Rop
 * @Date 2023/4/8 14:25
 * @description: 全局统一返回结果类
 */

@Data
public class Result<T> {

    /**
     * 返回码
     */
    private Integer code;

    /**
     * 返回信息
     */
    private String message;

    /**
     * 返回数据
     */
    private T data;

    public Result() {
    }

//    public Result<T> setData(T data) {
//        this.data = data;
//        return this;
//    }

    /**
     * 返回数据
     *
     * @param data 需要返回的数据
     * @param <T>  泛型
     * @return 结果
     */
    public static <T> Result<T> build(T data) {
        Result<T> result = new Result<>();
        if (Objects.nonNull(data)) {
            result.setData(data);
        }
        return result;
    }

    public static <T> Result<T> build(T data, Integer code, String message) {
        Result<T> result = build(data);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    public static <T> Result<T> build(T data, ResultCodeEnum resultCodeEnum) {
        Result<T> result = build(data);
        result.setCode(resultCodeEnum.getCode());
        result.setMessage(resultCodeEnum.getMsg());
        return result;
    }

    /**
     * 操作成功
     *
     * @param data 返回的数据
     * @param <T>  泛型
     * @return 返回的结果
     */
    public static <T> Result<T> ok(T data) {
        return build(data, ResultCodeEnum.SUCCESS);
    }

    public static <T> Result<T> ok() {
        return Result.ok(null);
    }

    /**
     * 操作失败
     *
     * @param data 返回的数据
     * @param <T>  泛型
     * @return 返回的结果
     */
    public static <T> Result<T> fail(T data) {
        return build(data, ResultCodeEnum.FAIL);
    }

    public static <T> Result<T> fail() {
        return Result.fail(null);
    }

    public Result<T> message(String msg) {
        this.setMessage(msg);
        return this;
    }

    public Result<T> code(Integer code) {
        this.setCode(code);
        return this;
    }
}
